package com.study.spark.scala.streaming.kafka.kafka

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.InputDStream
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.{CanCommitOffsets, HasOffsetRanges, KafkaUtils}
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
  * 方案一：使用kafka自身保存offset
  *
  * @author stephen
  * @create 2019-03-20 16:16
  * @since 1.0.0
  */
object KafkaDirectOffsetUseSelf {

  def main(args: Array[String]): Unit = {
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "localhost:9092", //指定Kafka的集群地址
      "key.deserializer" -> classOf[StringDeserializer], //指定key的反序列化器
      "value.deserializer" -> classOf[StringDeserializer], //指定值的反序列化器
      "group.id" -> "g_test", //consumer的分组id
      "auto.offset.reset" -> "earliest",
      "enable.auto.commit" -> (false: java.lang.Boolean) //是否自动提交offsets，也就是更新kafka里的offset，表示已经被消费过了
    )

    //定义消费主题topic
    val topics = Array("test")

    val conf: SparkConf = new SparkConf().setMaster("local[3]").setAppName("KafkaDirectWordCount")
    val ssc: StreamingContext = new StreamingContext(conf, Seconds(10))

    val kafkaStream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams))

    //使用kafka保存offset
    kafkaStream.foreachRDD { rdd =>
      if(!rdd.isEmpty()){
        // 获得offset
        val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges
        rdd.foreachPartition(iter=>{
          iter.foreach(line=>{
            // 简单的输出值
            println(line.value())
          })
        })
        // 异步提交offset
        kafkaStream.asInstanceOf[CanCommitOffsets].commitAsync(offsetRanges)
      }
    }
  }

}
